<template>
    <div id="mapBoxId"></div>
    <div class="option-btn__list">
        <button class="btn-item" @click="startMeasure">查询</button>
    </div>
</template>
<script lang="ts" setup>
import { TDMAP_TK } from '@/utils/constant';
import { View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { fromLonLat, toLonLat } from 'ol/proj';
import { XYZ } from 'ol/source';
import MapType from 'ol/Map.js';
import { defaults as defaultControls } from 'ol/control';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
import { bbox as bboxStrategy } from 'ol/loadingstrategy';
import GeoJSON from 'ol/format/GeoJSON';
// import { getCenter } from 'ol/extent';
import proj4 from 'proj4';
import { register } from 'ol/proj/proj4';
proj4.defs(
    'EPSG:4545',
    '+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
);
proj4.defs(
    'EPSG:3857',
    '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs'
);
register(proj4); // 将proj4注册到OpenLayers
let map: MapType;
let wfsServer: VectorLayer;

/**
 * 图层
 */
const getLayers = () => {
    // 天地图矢量图层
    const tdMapVectorLayer = new TileLayer({
        zIndex: 30,
        className: 'tdVector',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    // 天地图标注层
    const tdMapCvaLayer = new TileLayer({
        zIndex: 31,
        className: 'tdCva',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    wfsServer = new VectorLayer({
        zIndex: 32,
        className: 'wfsServer',
        visible: true,
        source: new VectorSource({
            format: new GeoJSON({}),
            url(extent) {
                console.log(extent);

                // return `http://192.168.2.72:8080/geoserver/woyou/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=woyou:ylzr1&maxFeatures=50&outputFormat=application/json&srsname=EPSG:3857`;
                return `http://192.168.2.48:/geoserver/testpipline/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=testpipline%3Apiplinepoint&maxFeatures=50&outputFormat=application%2Fjson`;
            }

            // strategy: bboxStrategy
        }),
        style: new Style({
            fill: new Fill({
                //填充颜色
                color: 'rgba(37,241,239,0.2)'
            }),
            stroke: new Stroke({
                color: '#FF0000',
                width: 4
            }),

            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: '#FF0000', //边框颜色
                    width: 3
                }),
                fill: new Fill({
                    color: '#ffffff' //填充颜色
                })
            })
        })
    });
    const layers = [tdMapVectorLayer, tdMapCvaLayer, wfsServer];
    return layers;
};
/**
 * 初始化地图
 */
const initMap = () => {
    const layers = getLayers();
    const view = new View({
        center: fromLonLat([109.7789, 38.2098]),
        projection: 'EPSG:3857',
        zoom: 12,
        // minZoom: 9,
        // maxZoom: 18,
        constrainResolution: true, // 设置缩放级别为整数
        smoothResolutionConstraint: false // 关闭无级缩放地图
    });
    map = new MapType({
        target: 'mapBoxId',
        layers,
        view,
        controls: defaultControls({
            zoom: false,
            rotate: false,
            attribution: false
        })
    });
    map.on('click', async function (evt) {
        console.log(toLonLat(evt.coordinate));
        startMeasure();
    });
    // wfsServer.getSource()?.on('featuresloadend', event => {
    //     const extent = wfsServer.getSource()?.getExtent();
    //     console.log('数据范围:', extent);
    //     console.log('地图视图范围:', map.getView().getExtent());
    // });

    // const center = getCenter([686350.9375, 4286662.5, 703097.0, 4301467.5]);
    // map?.getView().animate({
    //     center,
    //     zoom: 12,
    //     duration: 1000
    // });
};
/**
 * 开始测距
 */
const startMeasure = () => {
    const wfsServer = new VectorLayer({
        zIndex: 32,
        className: 'wfsServer',
        visible: true,
        source: new VectorSource({
            format: new GeoJSON(),
            url() {
                return `http://192.168.2.72:8080/geoserver/woyou/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=woyou:ylzr1&maxFeatures=50&outputFormat=application/json&srsname=EPSG:3857&CQL_FILTER=mt <> 'PE'`;
            },
            strategy: bboxStrategy
        }),
        style: new Style({
            fill: new Fill({
                //填充颜色
                color: 'rgba(37,241,239,0.2)'
            }),
            stroke: new Stroke({
                color: 'blue',
                width: 4
            }),

            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'blue', //边框颜色
                    width: 3
                }),
                fill: new Fill({
                    color: '#ffffff' //填充颜色
                })
            })
        })
    });

    map.addLayer(wfsServer);
    // const wfsFormat = new WFS({
    //     version: '1.0.0', // 或 '2.0.0'，需与服务端一致
    //     featureType: 'woyou:ylzr1' // WFS 图层名称
    // });

    // fetch(
    //     `http://192.168.2.72:8080/geoserver/woyou/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=woyou:ylzr&maxFeatures=50&outputFormat=application/json&srsname=EPSG:3857&CQL_FILTER=mt <> 'PE'`
    // )
    //     .then(response => response.json())
    //     .then(data => {
    //         const array = data.features.map((feature: any) => feature.properties);
    //         console.log(array); // 普通数组格式: [{材质: "铁", 直径: 100}, ...]
    //         const features = wfsFormat.readFeatures(data);
    //         console.log(features, '===features');

    //         wfsServer.getSource()?.addFeatures(features);
    //     });
};

/**
 * 销毁左侧地图
 */
const distoryMap = () => {
    map && map.setTarget();
    map && map.dispose();
};
onMounted(() => {
    initMap();
});
onBeforeUnmount(() => {
    distoryMap();
});
</script>
<style lang="scss" scoped>
#mapBoxId {
    width: 100vw;
    height: 100vh;
}
.option-btn__list {
    position: fixed;
    right: 20px;
    top: 20px;
    display: flex;
    z-index: 99;
    gap: 10px;
    .btn-item {
        border: none;
        background-color: #1e71ff;
        border-radius: 20px;
        padding: 0 20px;
        text-align: center;
        color: #fff;
        height: 36px;
        line-height: 36px;
        cursor: pointer;
    }
}
:deep(.ol-tooltip) {
    position: relative;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 4px;
    color: white;
    padding: 4px 8px;
    opacity: 0.7;
    white-space: nowrap;
    font-size: 12px;
    cursor: default;
    user-select: none;
}

:deep(.ol-tooltip-measure) {
    opacity: 1;
    font-weight: bold;
}

:deep(.ol-tooltip-static) {
    background-color: #3352ff;
    color: black;
    border: 1px solid white;
    color: #fff;
}

:deep(.ol-tooltip-measure),
:deep(.ol-tooltip-static) {
    &::before {
        border-top: 6px solid rgba(0, 0, 0, 0.5);
        border-right: 6px solid transparent;
        border-left: 6px solid transparent;
        content: '';
        position: absolute;
        bottom: -6px;
        margin-left: -7px;
        left: 50%;
    }
}

:deep(.ol-tooltip-static::before) {
    border-top-color: #3352ff;
}
</style>
